package com.czl.elm.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czl.elm.dao.RedParperMapper;
import com.czl.elm.dao.ShopMapper;
import com.czl.elm.domain.*;
import com.czl.elm.service.IRedParperService;
import com.czl.elm.util.ActionResult;
import com.czl.elm.util.RespPageBean;
import com.czl.elm.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class RedParperServiceImpl implements IRedParperService {

    @Autowired
    private RedParperMapper redParperMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Value("${redDayParper.officialNum}")
    private int OFFICAIALNUM;
    @Value("${redDayParper.shopNum}")
    private int SHOPNUM;
    /**
     * 在账户中加入每日优惠券
     *
     * @return
     * @param
     */
    @Override
    public ActionResult addDayRedParper() {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        List<RedParper> redParperList=new ArrayList<>();
        RedParper temp;
        String header="daily_";
        for(int i=0;i<OFFICAIALNUM;i++){
            temp=createRedParper(phoneName,getRandomRedShopParper(0),header,null);
            if(temp!=null)redParperList.add(temp);
        }
        for(int i=0;i<SHOPNUM;i++){
            temp=createRedParper(phoneName,getRandomRedShopParper(1),header,null);
            if(temp!=null)redParperList.add(temp);
        }

        return ActionResult.success("添加成功",redParperList);
    }

    /**
     * 获取用户的所有可用优惠券
     *
     * @return
     * @param currentPage
     * @param size
     */
    @Override
    public ActionResult getAllRedParper(Integer currentPage, Integer size) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        Page<RedParper> page=new Page<>(currentPage,size);
        LocalDateTime now=LocalDateTime.now();
        IPage<RedParper> res_page=redParperMapper.getAllRedParper(phoneName,page,now);
        RespPageBean res=new RespPageBean(res_page.getTotal(),setTag(res_page.getRecords()));
        return ActionResult.success("获取成功",res);
    }

    /**
     * 获取所有可用红包的数量
     * @return
     */
    @Override
    public ActionResult getAllRedParperNumber() {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        LocalDateTime now=LocalDateTime.now();
        Long res=redParperMapper.getAllRedParperNumber(phoneName,now);
        return ActionResult.success("获取成功",res);
    }

    /**
     * 获取最近获得的优惠券
     *
     * @return
     * @param currentPage
     * @param size
     */
    @Override
    public ActionResult getRecentRedParper(Integer currentPage, Integer size) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        Page<RedParper> page=new Page<>(currentPage,size);
        LocalDateTime now=LocalDateTime.now();
        LocalDateTime beforeday=now.minusDays(1);
        IPage<RedParper> res_page=redParperMapper.getRecentRedParper(phoneName,page,now,beforeday);
        RespPageBean res=new RespPageBean(res_page.getTotal(),setTag(res_page.getRecords()));
        return ActionResult.success("获取成功",res);
    }

    /**
     * 获取即将过去的优惠券
     *
     * @return
     * @param currentPage
     * @param size
     */
    @Override
    public ActionResult getWillExpireRedParper(Integer currentPage, Integer size) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        Page<RedParper> page=new Page<>(currentPage,size);
        LocalDateTime now=LocalDateTime.now();
        LocalDateTime afterday=now.plusDays(1);
        IPage<RedParper> res_page=redParperMapper.getWillExpireRedParper(phoneName,page,now,afterday);
        RespPageBean res=new RespPageBean(res_page.getTotal(),setTag(res_page.getRecords()));
        return ActionResult.success("获取成功",res);
    }

    /**
     * 获取该店铺可以使用的优惠券
     * @param
     * @return
     */
    @Override
    public ActionResult getUseRedParper(Integer shopId,Integer cost) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        LocalDateTime now=LocalDateTime.now();
        List<RedParper> res=redParperMapper.getUseRedParper(phoneName,shopId,cost,now);
        return ActionResult.success("获取成功",setTag(res));
    }

    /**
     * 获取该店不能使用的优惠券
     * @param
     * @return
     */
    @Override
    public ActionResult getNoUseRedParper(Integer shopId,Integer cost) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        LocalDateTime now=LocalDateTime.now();
        List<RedParper> res=redParperMapper.getNoUseRedParper(phoneName,shopId,cost,now);
        return ActionResult.success("获取成功",setTag(res));
    }

    @Override
    public ActionResult getUseRedParperNumber(Integer shopId, Integer cost) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        LocalDateTime now=LocalDateTime.now();
        Long res=redParperMapper.getUseRedParperNumber(phoneName,shopId,cost,now);
        return ActionResult.success("获取成功",res);
    }

    @Override
    public ActionResult getNoUseRedParperNumber(Integer shopId, Integer cost) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        LocalDateTime now=LocalDateTime.now();
        Long res=redParperMapper.getNoUseRedParperNumber(phoneName,shopId,cost,now);
        return ActionResult.success("获取成功",res);
    }

    /**
     * 获取历史记录
     * @return
     * @param currentPage
     * @param size
     */
    @Override
    public ActionResult getHistoryRedParper(Integer currentPage, Integer size) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        Page<RedParper> page=new Page<>(currentPage,size);
        LocalDateTime now=LocalDateTime.now();
        IPage<RedParper> res_page=redParperMapper.getHistoryRedParper(phoneName,page,now);
        RespPageBean res=new RespPageBean(res_page.getTotal(),setTag(res_page.getRecords()));
        return ActionResult.success("获取成功",res);
    }

    /**
     * 商家添加优惠券
     * 注意事项：startTime 如果是null则由获取当天的00：00：00为开始时间
     * endTime 如果为null 则是startTime+aftertime
     * 如果endTime由时间则以endTime时间为准
     * @param msg
     * @return
     */
    @Override
    public ActionResult addShopRedParper(Map<String, Object> msg) {

        boolean res=addShopRedParperFunction(msg);
        if(res){
            return ActionResult.success("生成成功");
        }else{
            return ActionResult.error("生成失败");
        }

    }
    private Boolean addShopRedParperFunction(Map<String, Object> msg){
        RedShopParper redShopParper=new RedShopParper();
        redShopParper.setRedShopParperId("daily_"+msg.get("shopId")+"_"+System.currentTimeMillis());
        redShopParper.setEnable((Integer)msg.get("enable"));
        redShopParper.setShopId((Integer)msg.get("shopId"));
        redShopParper.setAfterTime((Integer) msg.get("afterTime"));
        String start=(String)msg.getOrDefault("startTime",null);
        String end=(String)msg.getOrDefault("endTime",null);
        LocalDateTime startTime=null;
        if(start!=null)startTime= TimeUtil.StringToLocalDateTime(start);
        LocalDateTime endTime=null;
        if(end!=null)endTime=TimeUtil.StringToLocalDateTime(end);
        redShopParper.setStartTime(startTime);
        redShopParper.setEndTime(endTime);
        redShopParper.setReduction((Integer)msg.get("reduction"));
        redShopParper.setFullReduction((Integer)msg.get("fullReduction"));
        redParperMapper.addShopRedParper(redShopParper);
        return true;
    }





    /**
     * 获取该用户下该商店的优惠券
     * @param shopid
     * @return
     */
    private List<RedParper> getRedParperByShopId(Integer shopid){

        return null;

    }

    /**
     * 生成优惠券,优惠券id格式 phoneName_redpaper_当前毫秒数
     * @param
     * @return
     */
    public RedParper createRedParper(String phoneName, RedShopParper redShopParper, String header,String redParperId){
        if(redShopParper==null){
            System.out.println("无红包");
            return null;
        }
        RedParper redParper=new RedParper();

        //获取当前时间
        LocalDateTime now=LocalDateTime.now();   //这里的时util包下的
        Integer shopId=redShopParper.getShopId();
        redParper.setShopId(shopId);
        if(shopId!=0){
            Shop shop=shopMapper.selectShopBasicById(shopId);
            redParper.setShopUrl(shop.getShopUrl());
            redParper.setShopId(shopId);
            redParper.setShopName(shop.getShopName());
        }else{
            redParper.setShopUrl("/shop/elm.png");

            redParper.setShopName("通用红包");
        }
        if(redParperId==null)redParperId=header+phoneName+System.currentTimeMillis();
        redParper.setRedParperId(redParperId);
        redParper.setReduction(redShopParper.getReduction());
        redParper.setFullReduction(redShopParper.getFullReduction());
        redParper.setGetTime(now);
        redParper.setRedShopParperId(redShopParper.getRedShopParperId());
        redParper.setPhoneName(phoneName);
        redParper.setUseTime(null);
        LocalDateTime startTime;
        if(redShopParper.getStartTime()==null){

            startTime=LocalDateTime.of(now.getYear(),now.getMonth(),now.getDayOfMonth(),0,0,0);
        }else{

            startTime=redShopParper.getStartTime();
        }

        redParper.setStartTime(startTime);

        if(redShopParper.getEndTime()==null){
            LocalDateTime endTime=startTime.plusSeconds(redShopParper.getAfterTime());
            redParper.setEndTime(endTime);
        }else{
            redParper.setEndTime(redShopParper.getEndTime());
        }
        redParper.setShopId(redShopParper.getShopId());
        redParperMapper.saveCreateRedParper(redParper);
        return redParper;


    }

    /**
     * 随机获取一个的优惠
     * @param type 0:官方  1:商家
     * @return
     */
    private RedShopParper getRandomRedShopParper(Integer type){
        List<RedShopParper> list=redParperMapper.getRandomRedShopParper(type);

        Random random=new Random();
        if(list==null||list.size()==0)return null;
        return list.get(random.nextInt(list.size()));
    }

    @Override
    public ActionResult getFirstLoginToday() {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();

        Query query=new Query();
        LocalDate data=LocalDate.now();
        Criteria c=Criteria.where("_id").is(phoneName).and("loginTime").is(data);
        query.addCriteria(c);
        Map<String,Object> mgt =  mongoTemplate.findOne(query , Map.class,"firstLogin");
        if(mgt==null){
            mgt=new HashMap<>();
            mgt.put("_id",phoneName);
            mgt.put("loginTime",data);
            mgt.put("loginTimeDetail",data);
            mongoTemplate.save(mgt,"firstLogin");
            return ActionResult.success("今日首次登录",1);
        }else{
            return ActionResult.success("非今日首次登录",0);
        }

    }

    /**
     * 设置tag标签
     * @param redParpers
     * @return
     */
    private List<RedParper> setTag(List<RedParper> redParpers){

        for(RedParper paper:redParpers){
            if(paper.getUseTime()!=null){
                paper.setTag(-2);
            }else if(LocalDateTime.now().isAfter(paper.getEndTime())){
                paper.setTag(-1);
            }else if(LocalDateTime.now().isAfter(paper.getEndTime().minusDays(1))
                    &&LocalDateTime.now().isBefore(paper.getEndTime())){
                paper.setTag(2);
            }else if(LocalDateTime.now().isAfter(paper.getGetTime())
                    &&LocalDateTime.now().isBefore(paper.getGetTime().plusDays(1))){
                paper.setTag(1);
            }else{
                paper.setTag(0);
            }
        }
        return redParpers;

    }




    private RedShopParper getRedShopParperById(String redShopParperId){
        return redParperMapper.getRedShopParperById(redShopParperId);
    }

    @Override
    public ActionResult getredParperByIdWithActivity(String redParperId) {
        RedParper redParper=redParperMapper.getredParperById(redParperId);
        if(redParper==null)return ActionResult.error("获取不到");
        Map<String,Object> res=new HashMap<>();
        res.put("startTime",redParper.getStartTime());
        res.put("endTime",redParper.getEndTime());
        res.put("reduction",redParper.getReduction());
        return ActionResult.success("获取成功",res);
    }
}

